package server.handler.groupHandler;

import com.alibaba.fastjson.JSONObject;
import common.EnvelopeMessage;
import common.bodies.GroupShipBody;
import server.dao.GroupDao;
import server.dao.UserDao;
import server.handler.SimpleHandler;
import server.session.Session;

import java.util.List;

public class GroupInviteHandler implements SimpleHandler {
    @Override
    public void handle(EnvelopeMessage msg, Session session) {
        JSONObject body = msg.getBody();

        List<String> invitedFriends = body.getObject("list", List.class);

        Integer groupId = body.getInteger("groupId");
        String groupName = body.getString("groupName");

        for (String friendName : invitedFriends) {

            Integer friendId =  new UserDao(). getUserIdByUsername(friendName);

            if (friendId != null) {
                GroupShipBody ship = new GroupShipBody(friendId,groupId,groupName,1,1);
                new GroupDao().updateGroupShip(ship);
            } else {
                System.out.println("未找到用户: " + friendName);
                return ;
            }
        }
        JSONObject object = new JSONObject();
        object.put("status",true );
        EnvelopeMessage back = new EnvelopeMessage("group", "invite_result", object);
        String json = JSONObject.toJSONString(back);
        System.out.println("服务端返回"+json);
        session.send(json);
    }
}